package com.trendata.util;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import net.spy.memcached.MemcachedClient;

import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 缓存操作
 * 
 * @author: liubiao
 */
public class CacheUtil {
	private static MemcachedClient memcachedClient;
	private static Logger logger = Logger.getLogger("cacheLogger");
	static {
		memcachedClient = getMemcachedClient();
	}

	@SuppressWarnings("all")
	public static MemcachedClient getMemcachedClient() {
		if (memcachedClient == null) {
			memcachedClient = (MemcachedClient) new ClassPathXmlApplicationContext("applicationContext.xml").getBean("memcachedClient");
		}

		return memcachedClient;
	}

	/**
	 * 存缓存
	 * 
	 * @param key
	 *            键
	 * @param exp
	 *            过期时间，单位：秒
	 * @param o
	 *            值
	 */
	public static void put(String key, int exp, Object o) {
		try {
			getMemcachedClient().set(key, exp, o);
		} catch (Exception e) {
			logger.error("Error when put o to cache, key ==> " + key + ", exp ==> " + exp + ", o ==> "
					+ new JsonResult().setValue(o).toJsonString(), e);
		}
	}

	/**
	 * 删缓存
	 * 
	 * @param key
	 *            键
	 */
	public static void delete(String key) {
		getMemcachedClient().delete(key);
	}

	/**
	 * 查缓存
	 * 
	 * @param key
	 *            键
	 * @return
	 */
	public static Object get(String key) {
		Future<Object> f = null;
		try {
			f = getMemcachedClient().asyncGet(key);
			Object o = f.get(5, TimeUnit.SECONDS);
			if (o != null) {
				return o;
			}
		} catch (Exception e) {
			logger.error("Error when get o from cache, key = " + key, e);

			f.cancel(true);
		}

		return null;
	}
}
